<template>
  <div class="regulatory-page">
    <div class="return" @click="goBack">
      <Icon size="25" color="#000000" name="arrow-left" class="back" />
      <div class="title">
        <p class="text">订单中心</p>
      </div>
    </div>
    <van-tabs v-model="active" color="#FA6408" background="#F6F7F9" sticky animated title-inactive-color="#000000" title-active-color="#FA6408">
      <van-tab title="全部" name="全部">
        <div v-for="order in filteredOrders" :key="order.orderIdString " class="order-display">
          <div class="top-display">
            <p class="left-text">订单单号:{{ order.orderIdString }} <Icon size="14" color="#808080" name="arrow" /></p>
            <p class="right-text">{{ getOrderStatus(order.status) }}</p>
          </div>

            <van-card
                :title="order.title"
                :price="order.total"
                :desc="order.info"
                :thumb="require('@/'+order.imageUrl)"
                class="card"
            >
              <template #tags>
                <van-tag plain type="danger">{{ getOrderStatusLabel(order.status) }}</van-tag>
              </template>
              <template #footer>
                <van-button round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="handleCardClick(order)">订单详情</van-button>
                <van-button v-if="order.status === '0'" round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="payOrder(order.orderIdString )">去支付</van-button>
                <van-button v-else-if="order.status === '2'" round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="confirmReceipt(order.orderIdString )">确认收货</van-button>
                <van-button v-else-if="order.status === '3'" round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="reviewOrder(order.orderIdString )">去评价</van-button>
                <van-button v-else-if="order.status === '4'" round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="afterSales(order.orderIdString )">服务进度</van-button>
                <van-button v-if="order.status === '1'||order.status==='0'" round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="cancelOrder(order.orderIdString )">取消订单</van-button>
                <van-button v-if="order.status === '2'||order.status==='3'" round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="backOrder(order.orderIdString )">申请退单</van-button>
              </template>
            </van-card>
        </div>
      </van-tab>
      <van-tab title="待付款" name="待付款">
        <div v-for="order in filteredOrders" :key="order.orderIdString " class="order-display">
          <div class="top-display">
            <p class="left-text">{{ order.orderIdString  }} <Icon size="14" color="#808080" name="arrow" /></p>
            <p class="right-text">{{ getOrderStatus(order.status) }}</p>
          </div>
            <van-card
                :title="order.title"
                :price="order.total"
                :desc="order.info"
                :thumb="require('@/'+order.imageUrl)"
                class="card"
            >
              <template #tags>
                <van-tag plain type="danger">{{ getOrderStatusLabel(order.status) }}</van-tag>
              </template>
              <template #footer>
                <van-button round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="handleCardClick(order)">订单详情</van-button>
                <van-button  round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="payOrder(order.orderIdString )">去支付</van-button>
                <van-button  round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="cancelOrder(order.orderIdString )">取消订单</van-button>
              </template>
            </van-card>
        </div>
      </van-tab>
      <van-tab title="待发货" name="待发货">
        <div v-for="order in filteredOrders" :key="order.orderIdString " class="order-display">
          <div class="top-display">
            <p class="left-text">{{order.orderIdString }} <Icon size="14" color="#808080" name="arrow" /></p>
            <p class="right-text">{{ getOrderStatus(order.status) }}</p>
          </div>
            <van-card
                :title="order.title"
                :price="order.total"
                :desc="order.info"
                :thumb="require('@/'+order.imageUrl)"
                class="card"
            >
              <template #tags>
                <van-tag plain type="danger">{{ getOrderStatusLabel(order.status) }}</van-tag>
              </template>
              <template #footer>
                <van-button round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="handleCardClick(order)">订单详情</van-button>
                <van-button round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="remindShipment(order.orderIdString )">催发货</van-button>
                <van-button  round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="cancelOrder(order.orderIdString )">取消订单</van-button>
              </template>
            </van-card>
        </div>
      </van-tab>
      <van-tab title="待收货" name="待收货">
        <div v-for="order in filteredOrders" :key="order.orderIdString " class="order-display">
          <div class="top-display">
            <p class="left-text">{{ order.orderIdString  }} <Icon size="14" color="#808080" name="arrow" /></p>
            <p class="right-text">{{ getOrderStatus(order.status) }}</p>
          </div>

            <van-card
                :title="order.title"
                :price="order.total"
                :desc="order.info"
                :thumb="require('@/'+order.imageUrl)"
                class="card"
            >
              <template #tags>
                <van-tag plain type="danger">{{ getOrderStatusLabel(order.status) }}</van-tag>
              </template>
              <template #footer>
                <van-button round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="handleCardClick(order)">订单详情</van-button>
                <van-button round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="confirmReceipt(order.orderIdString )">确认收货</van-button>
                <van-button round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="backOrder(order.orderIdString )">申请退单</van-button>
              </template>
            </van-card>
        </div>
      </van-tab>
      <van-tab title="待评价" name="待评价">
        <div v-for="order in filteredOrders" :key="order.orderIdString " class="order-display">
          <div class="top-display">
            <p class="left-text">{{order.orderIdString }} <Icon size="14" color="#808080" name="arrow" /></p>
            <p class="right-text">{{ getOrderStatus(order.status) }}</p>
          </div>
            <van-card
                :title="order.title"
                :price="order.total"
                :desc="order.info"
                :thumb="require('@/'+order.imageUrl)"
                class="card"
            >
              <template #tags>
                <van-tag plain type="danger">{{ getOrderStatusLabel(order.status) }}</van-tag>
              </template>
              <template #footer>
                <van-button round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="handleCardClick(order)">订单详情</van-button>
                <van-button  round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="reviewOrder(order.orderIdString )">去评价</van-button>
                <van-button round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="backOrder(order.orderIdString )">申请退单</van-button>
              </template>
            </van-card>
        </div>
      </van-tab>
      <van-tab title="服务" name="服务">
        <div v-for="order in filteredOrders" :key="order.orderIdString " class="order-display">
          <div class="top-display">
            <p class="left-text">{{ order.orderIdString }} <Icon size="14" color="#808080" name="arrow" /></p>
            <p class="right-text">{{ getOrderStatus(order.status) }}</p>
          </div>
            <van-card
                :title="order.title"
                :price="order.total"
                :desc="order.info"
                :thumb="require('@/'+order.imageUrl)"
                class="card"
            >
              <template #tags>
                <van-tag plain type="danger">{{ getOrderStatusLabel(order.status) }}</van-tag>
              </template>
              <template #footer>
                <van-button round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="handleCardClick(order)">订单详情</van-button>
                <van-button round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="afterSales(order.orderIdString )">服务进度</van-button>
              </template>
            </van-card>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import {
  Button as VanButton,
  Card as VanCard,
  Dialog,
  Icon,
  Tab as VanTab,
  Tabs as VanTabs,
  Tag as VanTag,
  Toast
} from "vant";
import http from "@/plugins/http";
import Vue from "vue";

export default {
  name: "OrderCenterView",
  components: { Icon, VanTab, VanTabs, VanCard, VanTag, VanButton },
  data() {
    return {
      active: '全部',
      orders: [],
      title: "",
      tempOrder:{},
      tempProduct:{}
    };
  },
  activated() {
    this.fetchOrders().then(() => {
      this.fetchOrderItemsWithImages();
    });
  },
  computed: {
    filteredOrders() {
      if(this.orders !== null && this.orders.length > 0){
        switch (this.active) {
          case '全部':
            return this.orders;
          case '待付款':
            return this.orders.filter(order => order.status === '0');
          case '待发货':
            return this.orders.filter(order => order.status === '1');
          case '待收货':
            return this.orders.filter(order => order.status === '2');
          case '待评价':
            return this.orders.filter(order => order.status === '3');
          case '服务':
            return this.orders.filter(order => order.status === '4'||order.status==='6');
          default:
            return this.orders;
        }
      } else {
        return null;
      }
    }
  },
  methods: {
    async fetchOrderItemsWithImages() {
      // 确保 filteredOrders 是有效的数组
      if (!Array.isArray(this.orders)) {
        console.error("orders 不是有效的数组");
        return;
      }


      for (let order of this.orders) {
        try {
          const orderItems = await this.fetchOrderItems(order.orderIdString);
          if (orderItems && orderItems.length > 0) {
            const firstItem = orderItems[0];
            const imageUrl = await this.fetchProductImageById(firstItem.productId);
            const productName=orderItems[0].product.productName;
            if(productName){
              Vue.set(order, 'title', productName);
            }
            if (imageUrl) {
              Vue.set(order, 'imageUrl', imageUrl);  // 使用 Vue.set
            } else {
              console.error("未能获取到图片 URL");
            }
            console.log(order.imageUrl);
          }
        } catch (error) {
          console.error("处理订单项出错:", error);
        }
      }
    },


    async fetchOrderItems(orderId) {
      console.log(orderId);
      try {
        const response = await http.get(`/items/getById/${orderId}`);
        return response.data;
      } catch (error) {
        console.error("获取订单信息出错:", error);
        return [];
      }
    },

    async fetchProductImageById(productId) {
      try {
        const response = await http.get(`/product/${productId}`);
        return response.data.imageUrl;
      } catch (error) {
        console.error("获取商品图片出错:", error);
        return "";
      }
    },
    handleCardClick(order) {
      // 根据 orderId 执行导航逻辑
      this.$router.push({ name: 'OrderInfoView', params: { order:order} });
    },
    goBack() {
      this.$router.go(-1);
    },
    async fetchOrders() {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if (storedUser) {
        try {
          const response = await http.get(`/order/user/${storedUser}`);
          this.orders = response.data;
          await this.fetchOrderItemsWithImages();
        } catch (error) {
          console.error("获取订单信息出错:", error);
        }
      } else {
        console.error("没有用户登录");
      }
    },
    /*fetchSupplierNames() {
      if(this.orders !== null && this.orders.length > 0) {
        this.orders.forEach(order => {
          http.get(`/product/${order.product.productId}`)
              .then(response => {
                this.$set(order, 'supplierName', response.data.supplier.supplierName);
              })
              .catch(error => {
                console.error("获取商家信息出错:", error);
              });
        });
      }
    },*/
    getOrderStatus(status) {
      switch (status) {
        case '1':
          return '待发货';
        case '0':
          return '待支付';
        case '2':
          return '待收货';
        case '3':
          return '待评价';
        case '4':
          return '售后中';
        case '6':
          return '退单申请'
        default:
          return '已完成';
      }
    },
    getOrderStatusLabel(status) {
      switch (status) {
        case '1':
          return '待发货';
        case '0':
          return '待支付';
        case '2':
          return '待收货';
        case '3':
          return '待评价';
        case '4':
          return '售后中';
        case '6':
          return '退单申请'
        default:
          return '已完成';
      }
    },
    remindShipment(orderId) {
      // Logic to remind shipment
      Toast.success("已通知商家")
      console.log(`Remind shipment for order ${orderId}`);
    },
    backOrder(orderId){
      this.$router.push({ name: 'RefundView', params: { orderId: orderId } });
    },
    /*backOrder(orderId) {
      const refundReason=''
      this.$dialog.confirm({
        title: '申请退单',
        message: '请输入退单原因：',
        showCancelButton: true,
        showConfirmButton: true,
        showInput: true,
        inputValue: refundReason,
        confirmButtonText: '提交申请',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        this.refundReason = value; // 保存输入的退单原因
        if (this.refundReason.trim() !== '') {
          this.submitRefundRequest(orderId, refundReason);
        } else {
          this.$toast.fail('请填写退单原因！');
        }
      }).catch(() => {
        console.log('取消退单申请');
      });
    },
    async submitRefundRequest(orderId, reason) {
      try {
        const response = await this.$axios.post('/orders/refund', {
          orderId,
          reason, // 传递退单原因到后端
        });
        if (response.tatusCode==='200') {
          this.$toast.success('退单申请成功！');
          // 重新获取订单列表
          this.fetchOrders();
        } else {
          this.$toast.fail('退单申请失败，请稍后重试！');
        }
      } catch (error) {
        console.error(error);
        this.$toast.fail('网络错误，退单申请失败！');
      }
    },*/
    cancelOrder(orderId){
      http.get(`/order/delete/${orderId}`)
          .then(response => {
            if(response.statusCode==='200')
            {
              Toast.success(response.message)
              this.fetchOrders();
            }else{
              Toast.fail(response.message)
            }
          })
          .catch(error => {
            console.error("获取商家信息出错:", error);
          });
    },
    payOrder(orderId) {
      Dialog.confirm({
        title: '确认支付',
        message: '您确认要支付该订单吗？',
      })
          .then(() => {
            this.tempOrder = this.orders.find(order => order.orderIdString === orderId);
            if (!this.tempOrder) {
              console.error('未找到订单');
              return;
            }
            console.log(this.tempOrder)
            const payload = {
              orderId: this.tempOrder.orderIdString, // 注意这里要传递的是 orderId
              status: "1" // 将订单状态更新为已支付
            };
            http.post('/order/updateStatus', payload)
                .then(response => {
                  if (response.statusCode === "200")
                    Toast.success('支付成功');
                    this.fetchOrders();
                })
                .catch(error => {
                  Toast.fail('更新用户信息出错');
                  console.error("更新用户信息出错:", error);
                });
          })
          .catch(() => {
            Toast.success('取消支付');
          });
    },
    confirmReceipt(orderId) {
      this.tempOrder = this.orders.find(order => order.orderIdString === orderId);
      if (!this.tempOrder) {
        console.error('未找到订单');
        return;
      }

      const orderTotal = this.tempOrder.total; // 订单总额
      const storedUser = JSON.parse(sessionStorage.getItem("username"));

      if (!storedUser) {
        console.error('未找到用户信息');
        Toast.fail('用户信息缺失');
        return;
      }

      // 获取当前用户的积分和状态
      http.get(`/user/getUserInfo/${storedUser}`)
          .then(response => {
            const user = response.data;
            let newScore = user.score + orderTotal;
            let newStatus = user.userType;

            // 根据新积分更新用户状态
            if (newScore >= 1500) {
              newStatus = 3;
            } else if (newScore >= 1000) {
              newStatus = 2;
            } else if (newScore >= 500) {
              newStatus = 1;
            }

            // 更新用户积分和状态
            const updatePayload = {
              username: storedUser,
              score: newScore,
              userType: newStatus
            };

            return http.post('/user/updateUser', updatePayload);
          })
          .then(response => {
            if (response.statusCode==='200') {
              // 更新订单状态
              const payload = {
                orderId: this.tempOrder.orderIdString,
                status: "3" // 将订单状态更新为已收货
              };

              return http.post('/order/updateStatus', payload);
            } else {
              throw new Error('更新用户信息失败');
            }
          })
          .then(() => {
            Toast.success('确认收货成功');
            this.fetchOrders(); // 刷新订单数据
          })
          .catch(error => {
            Toast.fail('确认收货出错');
            console.error("确认收货出错:", error);
          });
    },
    reviewOrder(orderId) {
      this.$router.push({ name: 'GoReviewView', params: { orderId: orderId } });
    },
    afterSales(orderId) {
      console.log(`After-sales situation for order ${orderId}`);
    }
  },
  watch: {
    active() {
      switch (this.active) {
        case '待付款':
          this.active = '待付款';
          break;
        case '待发货':
          this.active = '待发货';
          break;
        case '待收货':
          this.active = '待收货';
          break;
        case '待评价':
          this.active = '待评价';
          break;
        case '服务':
          this.active = '服务';
          break;
        default:
          this.active = '全部';
          break;
      }
    }
  },
  mounted() {
    this.active=this.$route.params.active
  }
}
</script>

<style scoped>
.regulatory-page {
  background-color: #F6F7F9;
  height: 100vh;
}

.return {
  background-color: #FAEAEA;
  padding: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.back {
  position: absolute;
  left: 10px;
  text-decoration: none;
}

.title {
  display: flex;
  align-items: center;
}

.text {
  margin: 0;
  color: #000000;
  font-size: 16px;
}

.order-display {
  background-color: white;
  margin-left: 10px;
  margin-right: 10px;
  margin-top: 10px;
  padding-bottom: 10px;
  border-radius: 10px;
}

.top-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 10px;
  padding-right: 10px;
  cursor: pointer;
  padding-top: 15px;
}

.left-text {
  font-weight: bold;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.right-text {
  font-size: 14px;
  display: flex;
  align-items: center;
}

.card {
  background-color: #ffffff;
}

.right-text {
  color: #FA6408;
}
</style>
